import React, { useRef, useState, useEffect, useLayoutEffect } from "react"
import useMutateObserver from "../../hooks/useMutateObserver"

interface MutationObserverProps {
    options?: MutationObserverInit
    onMutate?: MutationCallback
    children: React.ReactElement
}

const MutationObserverCustom: React.FC<MutationObserverProps> = (props) => {
    const {
        options,
        onMutate = () => { },
        children,
    } = props

    const elementRef = useRef<HTMLElement>(null)
    const [target, setTarget] = useState<HTMLElement>()
    useMutateObserver(target!, onMutate, options)
    useLayoutEffect(() => {
        setTarget(elementRef.current!);
    }, []);
    if (!children) {
        return null;
    }

    return React.cloneElement(children, { ref: elementRef });
}

export function MutationObserverTest() {
    const [className, setClassName] = useState('aaa');

    useEffect(() => {
        setTimeout(() => setClassName('bbb'), 2000);
    }, []);
    const callback = function (mutationsList: MutationRecord[]) {
        console.log(mutationsList);
    };
    return (
        <div>
            <MutationObserverCustom onMutate={callback}>
                <div id="container">
                    <div className={className}>
                        {
                            className === 'aaa' ? <div>aaa</div> : <div>
                                <p>bbb</p>
                            </div>
                        }
                    </div>
                </div>
            </MutationObserverCustom>
        </div>
    )
}
